package com.simple.editor.action.impl;

import com.simple.editor.ApplicationContext;
import com.simple.editor.action.EditorException;
import com.simple.editor.converter.FileModelConverter;
import com.simple.editor.ui.FileModel;
import com.simple.editor.ui.InfoPane;
import com.simple.editor.ui.TabbedEditorPane;
import com.simple.editor.vcs.VcsClient;
import com.simple.editor.vcs.VcsClientRegistry;
import com.simple.editor.vcs.VcsFile;

import java.util.Map;

/**
 * {@link OpenEditorUIAction} handles user "Open File" action.
 * <p/>
 * Created with IntelliJ IDEA.
 * User: vlad
 * Date: 6/2/13
 * Time: 5:16 PM
 * To change this template use File | Settings | File Templates.
 */
public class OpenEditorUIAction extends AbstracEditorUIAction {

    private final ApplicationContext ctx;
    private final InfoPane infoPane;
    private final TabbedEditorPane editorPane;
    private final VcsClientRegistry vcsClientRegistry;

    public OpenEditorUIAction(final ApplicationContext ctx, final InfoPane infoPane,
                              final TabbedEditorPane editorPane, final VcsClientRegistry vcsClientRegistry) {
        this.ctx = ctx;
        this.infoPane = infoPane;
        this.editorPane = editorPane;
        this.vcsClientRegistry = vcsClientRegistry;
    }

    @Override
    public void perform(final FileModel... files) {
        if (files != null && files.length == 1) {
            final FileModel file = files[0];
            final boolean isNewFile;
            try {
                isNewFile = editorPane.openFile(file);
            } catch (EditorException ex) {
                infoPane.addError(String.format("File open error: %s", ex.getMessage()));
                return;
            }
            if (isNewFile) {
                final VcsClient vcsClient = vcsClientRegistry.getCurrentVcsClient();
                final Map<String, VcsFile> vcsFilesMap = FileModelConverter.convertFiles(file);

                // Refresh file status
                vcsClient.refreshStatus(new RefreshActionUICallbackImpl(vcsFilesMap, infoPane, ctx, file), vcsFilesMap.values());
            }
        }
    }
}

